package com.ypx.filter;

import com.alibaba.fastjson.JSON;
import com.ypx.common.BaseContext;
import com.ypx.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//value|urlPatterns 等价的，设置拦截的路径  /*代表拦截所有请求
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //定义直接放行的请求
    private final String[] paths = {
            "/employee/login",
            "/employee/logout",
            "/backend/page/login/login.html",
            "/front/page/login.html",
            "/user/login",
            "/user/logout",
            "/user/sendMsg",
            "/**/api/**",
            "/**/images/**",
            "/**/js/**",
            "/**/plugins/**",
            "/**/styles/**",
            "/**/*.ico",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };
    //路径匹配器
    AntPathMatcher pathMatcher = new AntPathMatcher();

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        log.info("LoginCheckFilter 的线程id:{}",Thread.currentThread().getId());

        //0.强制对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //1、获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("拦截到的请求：{}", uri);

        //2、判断本次请求是否需要处理
        /*if (uri.contains("/login") || uri.contains("/api") || uri.contains("/images")) {
            //放行
            chain.doFilter(req, resp);
        }*/
        //3、如果不需要处理，则直接放行
        for (String path : paths) {
            if (pathMatcher.match(path, uri)) {
                //匹配上了就放行,并且直接return,后面的逻辑不再处理
                chain.doFilter(req, resp);
                return;
            }
        }

        //4.1、判断登录状态，如果已登录，则直接放行
        Object employeeId = request.getSession().getAttribute("employeeId");
        if (employeeId != null) {
            //优化：将员工id设置到ThreadLocal中
            BaseContext.setCurrentId((Long) employeeId);
            //放行
            chain.doFilter(req, resp);
            return;
        }

        //4.2 判断移动端的用户是否登录
        Object userId = request.getSession().getAttribute("userId");
        if (userId != null) {
            //优化：将员工id设置到ThreadLocal中
            BaseContext.setCurrentId((Long) userId);
            //放行
            chain.doFilter(req, resp);
            return;
        }

        //5、如果未登录则返回未登录结果,跳转到登录页面
        /*if (uri.contains("/front")) {
            response.sendRedirect("/front/page/login.html");
        }
        if (uri.contains("/backend")) {
            response.sendRedirect("/backend/page/login/login.html");
        }*/
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

}
